package com.archermind.style.service;

import com.archermind.style.bean.User;
import com.feng.fengDUtil.BaseService;
import com.archermind.style.util.Search;
import com.feng.fengDUtil.Page;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class UserService extends BaseService {

    private static final Logger log = LoggerFactory.getLogger(UserService.class);
    
    /**
     * 根据账户查询用户信息
     * @param account 账户
     * @return 用户信息
     */
    public User findUserByAccount(String account) {
       return sql("select * from user where account = ?").one(User.class,account);
    }

    public boolean isUnique(String name,Integer id){
        ArrayList params = new ArrayList();
        String sql = "select 1 from user where account = ? ";
        params.add(name);
        if(id!=null){
            sql += " and id != ?";
            params.add(id);
        }
        Long one = sql(sql).one(Long.class, params.toArray());
        return one == null;
    }

   /* public List<Map> getMenuTree(User user){
        List<Map> list = sql("select * from menu").list(Map.class);
        return TreeUtil.geneTree(list);
    }*/
    
    /**
     * 修改密码
     * @param account 账户
     * @param newPassword 新密码
     * @return 用户
     */
    public void changePassword(String account,String newPassword) {
		// 获取账户匹配的用户信息
		User user = findUserByAccount(account);
		// 判断原密码与输入的密码是否一致
		user.setPassword(newPassword);
		List<Object[]> params = new ArrayList<>();
        params.add(new Object[]{newPassword,account});
		String sql = "update user set password=? where account=?";
		batch(sql,params);
	}

    public Page listUser(Page page, Search search) {
        ArrayList params = new ArrayList();
        String sql = "select u.*," +
                "(select s.name From user s where s.id = u.creator limit 1) as creatorName " +
                " from user u where 1=1 ";
        if(StringUtils.isNotEmpty(search.getName())){
            sql+=" and u.name like ? ";
            params.add(processLike(search.getName()));
        }
        sql+=" order by id desc";
        findPageList(Map.class,sql,page,params.toArray());
        return page;
    }

    public Page listRole(Page page, Search search) {
        ArrayList params = new ArrayList();
        String sql = "select u.*," +
                "(select s.name From user s where s.id = u.op limit 1) as opName " +
                " from sys_role u where 1=1 ";
        if(StringUtils.isNotEmpty(search.getName())){
            sql+=" and u.name like ? ";
            params.add(processLike(search.getName()));
        }
        sql+=" order by id desc";
        findPageList(Map.class,sql,page,params.toArray());
        return page;
    }
}
